import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class CampusNetworkAutoLogin {
    // 基础登录URL
    private static final String BASE_LOGIN_URL = "http://192.16.99.5/webauth.do";

    // 网络检测URL（轻量级）
    private static final String TEST_URL = "http://connect.rom.miui.com/generate_204";
    private static final int CHECK_INTERVAL = 4000; // 4秒检查一次

    // 你的登录凭证
    private static final String USERNAME = "账号";
    private static final String PASSWORD = "密码";

    // 从原始请求中提取的URL参数
    private static final Map<String, String> URL_PARAMS = new HashMap<String, String>() {{
        put("wlanacip", "192.16.99.2");
        put("wlanacname", "zkbras1");
        put("wlanuserip", "10.40.119.50");
        put("mac", "d4:93:90:1c:1b:e8");
        put("vlan", "3836");
        put("url", "http://1.1.1.1");
    }};

    // 从原始请求中提取的表单字段
    private static final Map<String, String> FORM_FIELDS = new HashMap<String, String>() {{
        put("loginType", "");
        put("auth_type", "0");
        put("isBindMac1", "0");
        put("pageid", "1");
        put("templatetype", "1");
        put("listbindmac", "0");
        put("recordmac", "0");
        put("isRemind", "1");
        put("loginTimes", "");
        put("groupId", "");
        put("distoken", "");
        put("echostr", "");
        put("isautoauth", "");
        put("mobile", "");
        put("userId", USERNAME);
        put("passwd", PASSWORD);
        put("remInfo", "on"); // 记住我功能
    }};

    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new NetworkCheckTask(), 0, CHECK_INTERVAL);

        System.out.println("校园网自动重连程序已启动，开始监控网络状态...");
    }

    static class NetworkCheckTask extends TimerTask {
        @Override
        public void run() {
            try {
                if (!isNetworkAvailable()) {
                    System.out.println("[" + getCurrentTime() + "] 检测到网络断开，尝试重新登录...");
                    boolean success = loginToCampusNetwork();
                    System.out.println("[" + getCurrentTime() + "] " + (success ? "登录成功" : "登录失败"));
                } else {
                    System.out.println("[" + getCurrentTime() + "] 网络连接正常");
                }
            } catch (Exception e) {
                System.err.println("[" + getCurrentTime() + "] 发生错误: " + e.getMessage());
            }
        }

        private String getCurrentTime() {
            return new java.text.SimpleDateFormat("HH:mm:ss").format(new java.util.Date());
        }

        private boolean isNetworkAvailable() {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(TEST_URL).openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(3000);
                connection.setReadTimeout(3000);
                connection.connect();
                return connection.getResponseCode() == 204;
            } catch (IOException e) {
                return false;
            }
        }

        private boolean loginToCampusNetwork() {
            HttpURLConnection conn = null;
            try {
                // 构建完整的登录URL（包含原始参数）
                StringBuilder loginUrl = new StringBuilder(BASE_LOGIN_URL);
                loginUrl.append("?");
                for (Map.Entry<String, String> entry : URL_PARAMS.entrySet()) {
                    loginUrl.append(entry.getKey());
                    loginUrl.append("=");
                    loginUrl.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()));
                    loginUrl.append("&");
                }
                loginUrl.deleteCharAt(loginUrl.length() - 1); // 移除最后一个&

                // 构建POST请求体
                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String, String> entry : FORM_FIELDS.entrySet()) {
                    if (postData.length() > 0) postData.append("&");
                    postData.append(entry.getKey());
                    postData.append("=");
                    postData.append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.name()));
                }

                byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);

                // 创建并配置HTTP连接
                conn = (HttpURLConnection) new URL(loginUrl.toString()).openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                conn.setDoOutput(true);
                conn.setConnectTimeout(5000);
                conn.setReadTimeout(5000);

                // 设置必要的请求头（模拟浏览器行为）
                conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0");
                conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7");
                conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
                conn.setRequestProperty("Cache-Control", "max-age=0");
                conn.setRequestProperty("Connection", "keep-alive");
                conn.setRequestProperty("Origin", "http://192.16.99.5");
                conn.setRequestProperty("Referer", loginUrl.toString());
                conn.setRequestProperty("Upgrade-Insecure-Requests", "1");

                // 发送POST数据
                try (OutputStream os = conn.getOutputStream()) {
                    os.write(postDataBytes);
                }

                // 检查响应
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应内容判断是否登录成功
                    try (BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()))) {
                        String line;
                        StringBuilder response = new StringBuilder();
                        while ((line = in.readLine()) != null) {
                            response.append(line);
                        }
                        // 根据实际响应内容判断是否登录成功
                        return !response.toString().contains("认证失败") &&
                                !response.toString().contains("密码错误");
                    }
                }
                return false;
            } catch (Exception e) {
                System.err.println("登录过程中发生错误: " + e.getMessage());
                return false;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }
    }
}